<?php
set_time_limit(120);

# Local authentication
include('functions.inc.php');
if (!isset($_GET['passphrase']) || $_GET['passphrase'] != $config['passphrase']) {
	die("Authentication error.\n");
}

$url = $_GET['url'];

header('Content-type: application/xml; charset=UTF-8');
header('Content-Disposition: inline; filename=rss.xml');

require_once('phputf8/validation.php');
require_once('phputf8/bad.php');

$html = get_web_page($url);

$need_utf8_conv = false;
foreach (explode("\r\n", $html) as $line) {
	if (stripos($line, 'encoding="ISO-8859-1') !== false) {
		$need_utf8_conv = true;
		$line = str_ireplace('encoding="ISO-8859-1"','encoding="UTF-8"',$line);
	}
	if (stripos($line, 'xmlns:media') !== false) {
		$line = ereg_replace('xmlns:media="[^"]+"','xmlns:media="http://search.yahoo.com/mrss/"',$line);
	}
	if (stripos($line, '<title') !== false) {
		$line = str_ireplace(array('&amp;quot;','&mdash;'), array('&#34;','—'), $line);
		$line = str_ireplace(array("<b>","<p>","</b>","</p>"), '', $line);
	}
	$line = ereg_replace('&#([0-9]{2})([^;^0-9])', '&#\1;\2', $line);
	$line = str_replace("  "," ",$line);
	$line = str_replace("&#039;","'",$line);
	$line = str_replace("&","&amp;",$line);
	$line = str_replace("&amp;#","&#",$line);
	$line = str_replace("&amp;amp;","&amp;",$line);
	$line = str_replace("&amp;amp;","&amp;",$line);
	$line = str_replace("&Uuml;","&amp;Uuml;",$line);
	$line = str_replace("&egrave;","&amp;egrave;",$line);
	$line = str_replace("&eacute;","&amp;eacute;",$line);
	$line = str_replace("&pound;","&amp;pound;",$line);
	$line = str_replace("&amp;#146;","'",$line);
	$line = str_replace("&amp;#147;","\"",$line);
	$line = str_replace("&amp;#148;","\"",$line);
	$line = str_replace("&amp;#151;","-",$line);
	$line = str_replace("&amp;lt;","&lt;",$line);
	$line = str_replace("&amp;gt;","&gt;",$line);
	$line = str_replace("&amp;quot;","\"",$line);
	$line = str_replace("wfw:commentRSS","wfw:commentRss",$line);
	$line = str_replace("<pubDate></pubDate>","<pubDate>".date('r', time())."</pubDate>",$line);
	$line = ereg_replace(' ([0-9]):([0-9]{2}):([0-9]{2})', ' 0\1:\2:\3', $line);
	if ($need_utf8_conv) {
		$line = utf8_encode($line);
	}
	$line = utf8_bad_replace($line);
	echo $line;
}
?>
